package xin.petstore.framework.cipher;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AESUtils {
    private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);

    public static byte[] encrypt(byte[] content, byte[] key, boolean md5Key, byte[] iv) {
        try {
            if (md5Key) {
                MessageDigest md = MessageDigest.getInstance("MD5");
                key = md.digest(key);
            }
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
            IvParameterSpec ivps = new IvParameterSpec(iv);
            cipher.init(1, skeySpec, ivps);
            return cipher.doFinal(content);
        } catch (Exception ex) {
            logger.error("encrypt error\n", ex);
        }
        return null;
    }

    public static String encryptString(String content, String key, boolean md5Key) {
        return Base64.encodeBase64String(encrypt(content.getBytes(), key.getBytes(), false, key.getBytes()));
    }

    public static byte[] decrypt(byte[] content, byte[] key, boolean md5Key, byte[] iv) {
        try {
            if (md5Key) {
                MessageDigest md = MessageDigest.getInstance("MD5");
                key = md.digest(key);
            }
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
            IvParameterSpec ivps = new IvParameterSpec(iv);
            cipher.init(2, skeySpec, ivps);
            return cipher.doFinal(content);
        } catch (Exception ex) {
            logger.error("decrypt error\n", ex);
        }
        return null;
    }

    public static String decryptString(String content, String key, boolean md5Key) throws UnsupportedEncodingException {
        return new String(decrypt(Base64.decodeBase64(content.getBytes("UTF-8")), key.getBytes(), false, key.getBytes()));
    }
}

